<?php

require_once( $CFG->dirroot . 'mod/folio/model/page.php');
require_once( $CFG->dirroot . 'mod/folio/model/page_permission.php');

require_once('base.php');
require_once('decoration.php');
require_once('artifact.php');
require_once('tags.php');

require_once( $CFG->dirroot . 'mod/folio/redirect.php');

class folio_PageEditor extends folio_BaseView {

    private $page;

    // Setup the vars
    function __construct( folio_page $page ) {

        // Cache page
        $this->page = $page;

        // Header
        $url = url;
        $this->html = <<< END

<!-- Main Content Table -->
<div id='folio_artifact_richeditor' class="yui-skin-sam">
END;

        // Add subsections.
        $this->Load( new folio_PageEditorHelp( $page ));

        $this->html .= <<< END
<table class="folio_page_settings" width=100%>
END;
        $this->Load( new folio_PageEditorTitle( $page ));
        $this->Load( new folio_PageEditorParentPage( $page ));
        $this->Load( new folio_PageEditorSecurity( $page ));
        $this->Load( new folio_TagAutocomplete($this->page));

        $this->html .= <<< END
</table>
END;

        $this->Load( new folio_PageEditorBody( $page ));
        $this->Load( new folio_PageEditorAttachments( $page ));

        $this->Load( new folio_Tooltip('folio_PageEditor_Title','Set the title of your page'));


        // Add Footer
        $this->html .= <<< END
</div>
<div style="clear:both;"><br/></div>
<!-- end main content table -->
END;


    }

    /**
     * Call to return a an array of artifacts' (or decorations) html code
     * to add to the rich editor
     * @param $objects An array of objects.
     */
    public function Add( $objects ) {
        $page_ident = -1;
        $html = ''; $js = '';

        // Get presentation style
        foreach ( $objects as $o ) {
            $page_ident = $o->page_ident;
            if( get_class($o) == 'folio_artifact' )
                $oc = new folio_ArtifactEditor($o);
            elseif ( get_class($o) == 'folio_decoration')
                $oc = new folio_DecorationEditor($o);
            else
                trigger_error('Unknown type "' . get_class($o) .
                              ' passed to folio_PageEditor::Add()');

            $html .= $oc->html();
            $js .= $oc->js();

        }

        // Wrap results
        $html .= <<< END
<!-- JS to initialize sortables -->
<script type="text/javascript">
// <![CDATA[

    folio_RichEditor_InitializeList({$page_ident});

    // Flash title as yellow
    //new Effect.Shake('{$o->handle()}');

    {$js}

    // Reset sort order
    folio_RichEditor_SetOrder({$page_ident});
// ]]>
</script>
END;
        return $html;
    }

}

/**
 * Setup the page title
 */
class folio_PageEditorHelp extends folio_BaseView {

    function __construct( folio_page $page ) {

//        $oTitle = __gettext('Page Instructions');
//            <span class="folio_page_sectiontitle">{$oTitle}</span>

        if( strlen($page->help) > 1 ) {

            $oRemove = __gettext('hide');

            $this->html .= <<< END
<div id='folio_PageEditor_Instruction'>
    <div width=100% id='folio_PageEditor_Instructions' class="folio_page_help">
        {$page->help}
        <a href="#" onclick="Effect.BlindUp('folio_PageEditor_Instructions');return false;">({$oRemove})</a>
    </div>
</div>
END;
        }
    }
}

/**
 * Setup the page title
 * Note that the element must be wrapped in a div with
 *  class="yui-skin-sam" tag.
 */
class folio_PageEditorTitle extends folio_BaseView {

    /**
     * Note that this can be called with new pages by
     * passing in null for the $page argument
     */
    function __construct( folio_page $page ) {

        $oTitle = __gettext('Title');
        $oTitleHelp = __gettext('Set the title of your page');
        $oClickTo = __gettext('Click here to set your page title');

        $url = url;
        $this->html .= <<< END
<tr><td class='folio_edit' width='90px'>
    <span class="folio_page_sectiontitle">{$oTitle}</span>:
</td><td class='folio_edit'>
    <div id='folio_page_title' class = 'folio_page_editable'>{$page->title}</div>
</td></tr>
END;

        $this->metatags = array();

        $this->js = <<< END
folio_ajax_makeEditable('{$page->page_ident}','page', 'title', 'folio_page_title');
END;

        // Load tooltip
        //$this->Load(new folio_Tooltip('folio_PageEditor_Title', $oTitleHelp));
        $this->Load(new folio_Tooltip('folio_page_title', $oClickTo));
    }
}

/**
 * Setup the page body editor
 */
class folio_PageEditorBody extends folio_BaseView {

    function __construct( folio_page $page ) {
        global $CFG;
        global $FOLIO_CFG;
        $url = url;

        // Setup redirect information.
        $redirect = new folio_redirect;
        $redirect->redirect_url = "{$url}page/{$page->page_ident}";
        $redirect->message = __gettext('Page Updated');
        $redirect = $redirect->html();

        // Create edit controls
        //$oBackToPage = "<img src='{$CFG->wwwroot}mod/folio/image/back.jpg' alt='" .
        //    __gettext('Back to Page') . "' border=0/>";
        $oClickTo = __gettext('Click here to edit the main text of your page');
        $oPageBody = __getText('Body');

        $this->js .= <<< END
folio_ajax_makeRichEditable('{$page->page_ident}', 'page', 'body', 'folio_pagebody');
END;

        $this->html .= <<< END
<br/>
<div id='folio_pagebody'  class='folio_page_editable' style='min-height:150px;'>{$page->body}</div>
<br/>
END;

        // Load tooltips
        $this->Load(new folio_Tooltip('folio_pagebody', $oClickTo));

    }
}

class folio_PageEditorAddAttachments extends folio_BaseView {

    private $page;

    function __construct( folio_page $page ) {
        $this->page = $page;
        $url = url;

        // Retrieve a list of resources.
        $user = folio_user::SelectWhereIdent($this->page->user_ident);

        $oText = __gettext('block of text');
        $oFile = __gettext('upload a file');
        $oEmbed = __gettext('embed html');
        $oContent = __gettext('use blogs or other uploaded content');

        $this->js .= <<< END

var folio_PageEditorAddAttachments = false;

// Reset all upload boxes
function folio_PageEditorAddAttachments_Menu_Reset() {
    if ( folio_PageEditorAddAttachments != false ) {
        $(folio_PageEditorAddAttachments).hide();
        //Effect.BlindUp('folio_PageEditorAddAttachments');
    }
}
// Show Embed
function folio_PageEditorAddAttachments_Show( id ) {
    if( id == folio_PageEditorAddAttachments) {
        // Currently selected, just hide.
        folio_PageEditorAddAttachments_Menu_Reset();
        folio_PageEditorAddAttachments = false;
    } else {
        // Not selected, hide current one.
        folio_PageEditorAddAttachments_Menu_Reset();
        folio_PageEditorAddAttachments = id;
        Effect.BlindDown(id);
    }
}
END;
        // Add the main menu for adding new attachments.
        $this->html .= <<< END
<div class='folio_PageEditorAddAttachments_Menu'>
Add a
<a href="javascript:folio_Decoration_AddText({$this->page->page_ident},'label');">
    {$oText}</a>,
<a href="#" onclick="folio_PageEditorAddAttachments_Show('folio_PageEditorAddAttachments_File'); return false;">
    {$oFile}</a>, or
<a href="#" onclick="folio_PageEditorAddAttachments_Show('folio_PageEditorAddAttachments_Embed');return false;">
    {$oEmbed}</a>
</div>
END;

/*
 , or
<a href="#" onclick="folio_PageEditorAddAttachments_Show('folio_PageEditorAddAttachments_Content'); return false;">
    {$oContent}</a>
*/

        // Add the embed box for new attachments.
        $this->html .= <<< END
<div id='folio_PageEditorAddAttachments_Embed' style="display:none;">
Use the below box to embed content from online services like Picassa or Youtube.<br/>
<input id='folio_PageEditorAddAttachments_Embed_html' />
<br/>
<input id='folio_PageEditorAddAttachments_Embed_submit'
    onclick="folio_Decoration_AddHtml({$page->page_ident});" type="button" value="Save"/>
or
<input id='folio_PageEditorAddAttachments_Embed_cancel'
    onclick="Effect.BlindUp('folio_PageEditorAddAttachments_Embed');return false;"
    type="button" value="Cancel"/>
</div>
END;

        // File box to upload
        $oUpload = __gettext('Upload a file into the page');

        $this->html .= <<< END
<div id='folio_PageEditorAddAttachments_File' style="display:none;">
    {$oUpload}<br/>
    <form action="{$url}mod/folio/ajax/file_insert.php"
        enctype="multipart/form-data" method="post" id="folio_RichEditor_FileUpload_form">
    <input type="file" name="testFile"/>
    <input type="hidden" name="page_ident" value={$this->page->page_ident} />
    <input type="button" id="uploadButton" value="Upload"/>
    </form>
    <span id='folio_RichEditor_FileUpload_uploading' style="display:none;">
        Uploading <img src="{$url}mod/folio/image/working.gif" alt="working..." />
    </span>
</div>

END;

        // Load Resource 'Content Tree'
        /*
        $resources = new folio_ResourceTree( $this->page, $user ) ;
        $this->metatags = $resources->metatags();
        $this->js .= $resources->js();
        $addcontent = <<< END
<div id='folio_PageEditorAddAttachments_Content' style="display:none;">
<span class="folio_page_sectiontitle">Your Content</span>
END;
        $addcontent .= $resources->html();
        $addcontent .= <<< END
</div>
END;
        */

    }

}


/**
 * Setup the page attachments editor
 */
class folio_PageEditorAttachments extends folio_BaseView {

    function __construct( folio_page $page ) {

        // Internal check, not for security (that's handled by the html page
        //      being requested), but as a sanity check before we pull the
        //      userid.
        if( !isloggedin() ) {
            trigger_error('You must be logged in to edit this page', E_USER_ERROR);
        }

        $url = url; $html = ''; $js = '';

        // Retrieve supporting objects for the page.
        $artifacts = folio_artifact::SelectWherePageIdent( $page->page_ident );
        $decorations = folio_decoration::SelectWherePageIdent( $page->page_ident );
        $user = folio_user::SelectWhereIdent( $page->user_ident );

        // Build javascript for attachments
        $this->js = <<< END
    YAHOO.util.Event.on(window, 'load', init);
    folio_RichEditor_InitializeList({$page->page_ident});
END;

        // Build edit control for the page title.
        $oContents = __gettext("Attachments");
        $oContentsHelp = __gettext('Order attachments by clicking and draging on the paperclip, add items through the sidebar, ' .
            ' and remove them with the red button.');

        $oText = __gettext('block of text');

        // Build the beginning html
        $this->html .=  <<< END
<h1 id='folio_attachments'>{$oContents}</h1>
END;

        // Load the 'add attachments' menu.
        $this->Load(new folio_PageEditorAddAttachments($page));

        // Load tooltip
        $this->Load(new folio_Tooltip('folio_attachments', $oContentsHelp));

        // Add list where attachments will be loaded.
        $this->html .= <<< END
<ul class="sortabledemo" id="folio_RichEditor_list">
END;



        // Load decorations & artifacts according to their keys located
        //      in the page.
        if( strlen( $page->attachments ) > 0 ) {
            $objects = split(",",$page->attachments);
            foreach( $objects as $o) {
                // Load object
                if( substr( $o, 0, 8 ) == 'artifact' )
                    $object = new folio_ArtifactEditor(
                                    $artifacts[ substr( $o, 8 ) ] );
                elseif ( substr( $o, 0, 10 ) == 'decoration' )
                    $object = new folio_DecorationEditor(
                                    $decorations[ substr( $o, 10 ) ] );
                else
                    trigger_error('Invalid attachments value "' . $o . '" for page_ident ' .
                                  $page->page_ident .
                                  ' for folio_PageEditorAttachments', E_USER_ERROR);

                // Cache the dec or artifact
                $this->Load($object);
            }
        }

        // Finish the page shell
        $this->html .=  <<< END
</ul><br/>
END;

        // Load the required Metatags
        $this->metatags = array(
                            'mod/tinymce/lib/jscripts/tiny_mce/tiny_mce.js',
                            'mod/folio/lib/scriptaculous-js-1.7.0/lib/prototype.js',
                            'mod/folio/lib/scriptaculous-js-1.7.0/src/scriptaculous.js',
                            'mod/folio/lib/yui_2.4.1/build/yahoo/yahoo-min.js',
                            'mod/folio/lib/yui_2.4.1/build/yahoo-dom-event/yahoo-dom-event.js',
                            'mod/folio/lib/yui_2.4.1/build/connection/connection-min.js',
                            'mod/folio/js/view_page.js',
                            'mod/folio/js/view_ajax.js',
                            'mod/folio/css/edit.css',
                            'mod/folio/js/edit.js'
                        );
    }
}

class folio_PageEditorParentPage extends folio_BaseView {
    private $page;

    function __construct( folio_page $page ) {
        $this->page = $page;

        if( $this->page->IsHomepage()) {
            // Don't allow changing parent for a homepage, return empty.
        } else {
            // Load js & html vars.
            folio_PageEditorParentPage::_html();
            folio_PageEditorParentPage::_js();
        }
    }

    private function _js() {
        $pre = 'folio_PageEditorParentPage';
        $edit = $pre . '_edit';
        $view = $pre . '_view';
        $value1 = $pre . '_parent';
        $F = '$F';
        $url = url;

        $this->js = <<< END
// Use to make the parentpage editable.
Event.observe('{$pre}_view', 'click',
    function(){{$pre}_edit({$this->page->page_ident})}, false);
Event.observe('{$pre}_view', 'mouseover',
    function(){folio_ajax_showAsEditable($('{$pre}_view'))}, false);
Event.observe('{$pre}_view', 'mouseout',
    function(){folio_ajax_showAsEditable($('{$pre}_view'), true)}, false);
var {$pre}_initcomplete = false;

// Function for editing
function {$pre}_edit( iIdent ){
    // Make the fields reversed visibility.

    Element.show('{$edit}');
    Element.hide('{$view}');

    // Add event handlers if this is the first time.
    if( {$pre}_initcomplete == false) {
        Event.observe('{$pre}_save', 'click', function(){{$pre}_saveChanges(iIdent)}, false);
        Event.observe('{$pre}_cancel', 'click', function(){{$pre}_cleanUp(iIdent)}, false);
        {$pre}_initcomplete  = true;
    }
}

function {$pre}_saveChanges(iIdent){

    var v1 =  encodeURIComponent($F('{$value1}'));

    {$pre}_cleanUp(iIdent);
    obj = $('{$view}');
    obj.innerHTML    = "Saving...";

    var success    = function(t){{$pre}_editComplete(t, obj);}
    var failure    = function(t){{$pre}_editFailed(t, obj);}

    var url = '{$url}mod/folio/ajax/page_update.php';
    var pars = 'page_ident=' + iIdent + '&folio_redirect_echo=parentpage_title' +
        '&parentpage_ident='+v1;
    var myAjax = new Ajax.Request(url,
        {method:'post', postBody:pars, onSuccess:success, onFailure:failure});
}

function {$pre}_cleanUp(iIdent){

    // Toggle Visibility.
    Element.hide('{$edit}');
    Element.show('{$view}');
}

function {$pre}_editComplete(t, obj){
    $('{$view}').innerHTML    = t.responseText;
}

function {$pre}_editFailed(t, obj){
    $('{$view}').innerHTML    = 'Sorry, the update failed.';
}
END;
    }

    private function _html() {
        global $CFG;
        $url = url;
        $pre = 'folio_PageEditorParentPage';
        $page = $this->page;

        if( $page == null )
            trigger_error('You must pass a page value to ' .
                          'folio_pageEditorParentPage',E_USER_ERROR);

        // Grab the page owner & homepage
        $user = folio_user::SelectWhereIdent( $page->user_ident);
        $homepage = folio_page::SelectHomepage($user);
        if( $homepage === false )
            trigger_error('You can not folio_PageEditorParentPage for a ' .
                          'new homepage', E_USER_ERROR);

        // Set the default value.
        $parentpage_ident = $this->page->parentpage_ident;
        $parentpage = folio_page::SelectWherePageIdent($parentpage_ident);

        $oWhere = __gettext('Which page would you like this to be located under?');
        $html = folio_PageEditorParentPage::recurse($this->page, $user,$homepage,$parentpage_ident);
        $oTitle = __gettext('Location');

        $this->html = <<< END
<tr><td class='folio_edit'>
    <span class="folio_page_sectiontitle">{$oTitle}</span>:
</td><td class='folio_edit'>
    <form>
        <div id="{$pre}_edit" style="display: none">
            <select id='{$pre}_parent' style="width:100%;">
            {$html}
            </select>
            <br/>
            <input id="{$pre}_save" type="button" value="SAVE" />
                OR <input id="{$pre}_cancel" type="button" value="CANCEL" />
        </div>
        <div id={$pre}_view class = 'folio_page_editable'>{$parentpage->title}</div>
    </form>
</td></tr>
END;
    }


    /**
     * Recursive function for building the parentcontrol.
     *
     * @param folio_page $editpage The page we're finding a new location for
     * @param folio_user $user Owner of the page
     * @param folio_page $page Page currently being recursed to
     * @param int $parentpage_ident Default value for the parentpage.
     * @param string $depth OPTIONAL, don't use for first call.
     */
    private function recurse( $editpage, $user, $page, $parentpage_ident, $depth = '') {

        // Build labels.
        if ($page->page_ident == $parentpage_ident ) {
            $oSelected = ' SELECTED ';
        } else {
            $oSelected = '';
        }

        // Build label
        $run_result = "<OPTION VALUE={$page->page_ident} {$oSelected}>" .
                        $depth . $page->title . "\n";

        // Grab child pages.
        $pages = folio_page::SelectWhereParentpageIdent($page->page_ident);

        // Recurse for each child page.
        $depth .= "&nbsp;&nbsp;&nbsp;";
        if ( $pages !== false ) {
            // Iterate
            foreach ($pages as $p) {
                // Don't show the editpage or any of its children.
                if (
                    $editpage == false OR
                    ( $editpage !== false AND $p->page_ident != $editpage->page_ident )
                    ) {
                    $run_result .= folio_PageEditorParentPage::recurse(
                                $editpage, $user, $p, $parentpage_ident, $depth );
                }
            }
        }

        // Return results.
        return $run_result;
    }
}

class folio_PageEditorSecurity extends folio_BaseView {
    private $page;

    function __construct( folio_page $page ) {
        $this->page = $page;

        // Load js & html vars.
        folio_PageEditorSecurity::_html();
        folio_PageEditorSecurity::_js();

    }

    private function _js() {
        $pre = 'folio_PageEditorSecurity';
        $edit = $pre . '_edit';
        $view = $pre . '_view';
        $value1 = $pre . '_accesslevel';
        $value2 = $pre . '_global';
        $F = '$F';
        $url = url;

        $this->js = <<< END
// Use to make the security editable.
Event.observe('{$pre}_view', 'click',
    function(){{$pre}_edit({$this->page->page_ident})}, false);
Event.observe('{$pre}_view', 'mouseover',
    function(){folio_ajax_showAsEditable($('{$pre}_view'))}, false);
Event.observe('{$pre}_view', 'mouseout',
    function(){folio_ajax_showAsEditable($('{$pre}_view'), true)}, false);
var {$pre}_initcomplete = false;

// Function for editing
function {$pre}_edit( iIdent ){
    // Make the fields reversed visibility.

    Element.show('{$edit}');
    Element.hide('{$view}');

    // Add event handlers if this is the first time.
    if( {$pre}_initcomplete  == false) {
        Event.observe('{$pre}_save', 'click', function(){{$pre}_saveChanges(iIdent)}, false);
        Event.observe('{$pre}_cancel', 'click', function(){{$pre}_cleanUp(iIdent)}, false);
        {$pre}_initcomplete  = true;
    }
}

function {$pre}_saveChanges(iIdent){

    var v1 =  encodeURIComponent($F('{$value1}'));
    var v2 =  encodeURIComponent($F('{$value2}'));

    {$pre}_cleanUp(iIdent);
    obj = $('{$view}');
    obj.innerHTML    = "Saving...";

    var success    = function(t){{$pre}_editComplete(t, obj);}
    var failure    = function(t){{$pre}_editFailed(t, obj);}

    var url = '{$url}mod/folio/ajax/page_update.php';
    var pars = 'page_ident=' + iIdent + '&folio_redirect_echo=accesslevel' +
        '&accesslevel='+v1+'&global='+v2;
    var myAjax = new Ajax.Request(url,
        {method:'post', postBody:pars, onSuccess:success, onFailure:failure});
}

function {$pre}_cleanUp(iIdent){

    // Toggle Visibility.
    Element.hide('{$edit}');
    Element.show('{$view}');
}

function {$pre}_editComplete(t, obj){
    $('{$view}').innerHTML    = t.responseText;
}

function {$pre}_editFailed(t, obj){
    $('{$view}').innerHTML    = 'Sorry, the update failed.';
}
END;
    }

    private function _html() {
        global $CFG;
        global $FOLIO_CFG;
        $user = folio_user::SelectWhereIdent( $this->page->user_ident);

        $url = url;
        $accesslevel = '';
        $pre = 'folio_PageEditorSecurity';

        // Build Labels
        $labels = array(
            'person-private'=>__gettext('Private (other people can not read or edit)'),
            'person-moderated'=> __gettext('Moderated (other people can read, but not edit)'),
            'person-public'=> __gettext('Public (everyone has full access)'),
            'community-private'=> __gettext('Private (only community members can read or edit)'),
            'community-moderated'=>__gettext('Moderated (everyone can can read, but only community members can edit)'),
            'community-public'=>__gettext('Public (everyone has full access)')
            );

        // Build the current setting.
        if ( !!$this->page ) {
            // Find out what security-level we're set at.
            $permissions = folio_page_permission::SelectWherePageIdent( $this->page->page_ident );

            if (!$permissions) {
                // No results returned, set to default
                $accesslevel = $FOLIO_CFG->page_defaultpermission;
            } else {
                foreach( $permissions as $permission ) {
                        $accesslevel = $permission->accesslevel;
                }
            }
            $security_ident = $this->page->page_ident;
        } else {
            // New, so st to the default
            $accesslevel = $FOLIO_CFG->page_defaultpermission;
            $security_ident = -1;
        }

        // Figure out which option is selected & set value.
        $oPublic = ''; $oModerated = ''; $oPrivate = '';
        if ( $accesslevel == 'PUBLIC' ) {
            $oPublic = ' SELECTED=true ';
        } elseif ( $accesslevel == 'MODERATED' ) {
            $oModerated = ' SELECTED=true ';
        } elseif ( $accesslevel == 'PRIVATE' ) {
            $oPrivate = ' SELECTED=true ';
        }

        //$label = __gettext('Please choose a security level for this page:');
        $oGlobal= __gettext('Change all pages');

        // Build result
        $run_result = <<< END
            <div id="{$pre}_edit" style="display: none">
                <SELECT id="{$pre}_accesslevel">
                    <OPTION VALUE="PUBLIC" {$oPublic}>{$labels[$user->user_type . '-public']}
                    <OPTION VALUE="MODERATED" {$oModerated}>{$labels[$user->user_type . '-moderated']}
                    <OPTION VALUE="PRIVATE" {$oPrivate}>{$labels[$user->user_type . '-private']}
                </SELECT>
                <input id="{$pre}_global" type="checkbox" />{$oGlobal}<br/>
                <input id="{$pre}_save" type="button" value="SAVE" />
                    OR <input id="{$pre}_cancel" type="button" value="CANCEL" />
            </div>
            <div id={$pre}_view class = 'folio_page_editable'>{$accesslevel}</div>
END;
        $oTitle = __gettext('Permissions');

        $this->html = <<< END
<tr><td class='folio_edit'>
    <span class="folio_page_sectiontitle">{$oTitle}</span>:
</td><td class='folio_edit'>
        <form>
        {$run_result}
        </form>
</td></tr>
END;

    }



    /**
     * Call to retrieve input from _POST and make the corresponding security updates and $page updates.
     * Assume that we have permissions.
     *
     * @param folio_page $page The page to update with $_POST
     * @return boolean
     */
    public function htmlUpdateFromPost( $page, $accesslevel, $global ) {

        if( $global == true ) {
            // Set the homepage and all children pages.
            $user = folio_user::SelectWhereIdent($page->user_ident);
            $homepage = folio_page::SelectHomepage($user);
            return folio_PageEditorSecurity::htmlUpdateFromPost_Page(
                                $homepage, 'custom', $accesslevel, true);
        } else {
            // Set the current page
            return folio_PageEditorSecurity::htmlUpdateFromPost_Page(
                                $page, 'custom', $accesslevel, false);
        }

    }

    /**
     * Called for each page to be updated by htmlUpdateFromPage.  Can recurse.
     *
     * @param folio_page $page Page to update.
     * @param string $security_type Custom or Parent
     * @param string $accesslevel The new security level.
     * @param boolean $recurse Should we also set child pages?
     * @return boolean
     */
    private function htmlUpdateFromPost_Page($page, $security_type, $accesslevel, $recurse ) {

        // Check to see if we're inheriting.
        $security_ident = $page->page_ident;

        // Validate accesslevel
        if ($accesslevel <> 'PUBLIC' & $accesslevel <> 'MODERATED' & $accesslevel <> 'PRIVATE') {
            error('Invalid access level passed to page_page_permission::htmlUpdateFromPost (' . $accesslevel . ')' );
        }

        // Test to see if the record already exists.
        $permissions = folio_page_permission::SelectWherePageIdent( $page->page_ident );

        if ( !$permissions ) {

            // Insert a new security record.
            $security = new StdClass;
            $security->security_ident = $security_ident;
            $security->user_ident = -1;  // NOTE: Not currently used.
            $security->accesslevel = $accesslevel;
            insert_record('folio_page_security',$security);

        } else {
            // Update security record(s)

            set_field('folio_page_security', 'accesslevel', $accesslevel,
                'security_ident', $security_ident);
        }

        // Ensure that the page has the proper security record.
        if( $page->security_ident <> $security_ident ) {
            $page->security_ident = $security_ident;
            $page->Update( );
        }

        // Do the same for all children pages.
        if( $recurse ) {
            $children = folio_page::SelectWhereParentpageIdent($page->page_ident);
            if( $children) {
                foreach( $children as $child) {
                    folio_PageEditorSecurity::htmlUpdateFromPost_Page($child, $security_type, $accesslevel, true);
                }
            }
        }

        // Return true to show success.
        return true;
    }


    /**
     * Updates the passed page with the newly set parentpage value without saving in the db.
     *
     * @param folio_page $page
     * @return folio_page
     */
    public function redirect( $page ) {
        if( isset($_POST['folio_page_parentpage_ident'] ) ) {
            $page->parentpage_ident = intval($_POST['folio_page_parentpage_ident']);
        }
        return $page;
    }


}

?>
